<template>
  <a-modal
    :visible="visible"
    :title="title"
    :confirmLoading="confirmLoading"
    :destroyOnClose="true"
    :maskClosable="false"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-form-model
      ref="rulesForm"
      :model="form" :label-col="labelCol" :wrapper-col="wrapperCol"
      :rules="rules"
    >
      <a-form-model-item :label="`${billInfo}款金额`" prop="amount">
        <a-input-number v-model="form.amount" :min="0" :precision="2" :max="999999999999.99"/> {{amountType}}
      </a-form-model-item>
      <a-form-model-item :label="`${billInfo}款账号`" prop="capitalAccountId">
        <input class="ant-input" :value="chosenItem0 || form.capitalAccount" readonly @click="chooseAccount"/>
      </a-form-model-item>
      <a-form-model-item :label="`${billInfo}款银行`" style="margin:0">{{chosenItem1 || form.capitalBank || '--'}}</a-form-model-item>
      <a-form-model-item label="所属公司">{{chosenItem2 || form.deptName || '--'}}</a-form-model-item>
      <a-form-model-item :label="`${accountInfo}款账号`">
        <a-input v-model="form.transactionAccount" :max-length="20"/>
      </a-form-model-item>
      <a-form-model-item :label="`${accountInfo}款银行`">
        <a-input v-model="form.transactionBank" :max-length="20"/>
      </a-form-model-item>
      <a-form-model-item :label="`${billInfo}款日期`" prop="transactionDate">
        <a-date-picker :value="transactionDateMoment" @change="onChangeDate" :disabled-date="disabledDate"><a-icon slot="suffixIcon" type="calendar" /></a-date-picker>
      </a-form-model-item>
      <a-form-model-item label="银行凭证" prop="bankVoucher" style="margin-bottom:0">
        <upload :uploadName="'bankVoucher'"
          :fatherList="form.bankVoucher ? form.bankVoucher.split(',') : []"
          :length="1"
          @uploadFile="uploadFile"
        ></upload>
      </a-form-model-item>
      <a-form-model-item label="备注">
        <a-textarea v-model="form.remark" :rows="3" :max-length="200"></a-textarea>
      </a-form-model-item>
    </a-form-model>

    <!-- 选择资金账户modal -->
    <a-modal :visible="accountVisible" title="选择资金账户"
      :destroyOnClose="true"
      :maskClosable="false"
      width='640px'
      @ok="handleOk2"
      @cancel="handleCancel2">
      <a-form layout="inline">
        <a-form-item label="资金账户">
          <a-input v-model="searchForm.account"></a-input>
        </a-form-item>
        <a-form-item label="所属公司">
          <a-tree-select class="selectWidth"
            v-model="searchForm.deptId"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :load-data="onLoadData"
            :tree-data="deptTreeData"
          >
          </a-tree-select>
        </a-form-item>
        <a-form-item label="开户行">
          <a-input v-model="searchForm.bank"></a-input>
        </a-form-item>
        <a-form-item label="币种">
          <a-select v-model="searchForm.currencyType" class="selectWidth" >
            <a-select-option key>全部</a-select-option>
            <a-select-option key="CNY">人民币</a-select-option>
            <a-select-option key="USD">美金</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item>
          <a-button type="primary" @click="handleSubmit">查询</a-button>
        </a-form-item>
      </a-form>

      <a-radio-group v-model="chosenAccount">
        <a-table :columns="columns" :data-source="tableData" :loading="loading" class="tableMargin" :pagination="false" rowKey="id">
          <template slot="rn" slot-scope="text, record, index">{{index + 1}}</template>
          <template slot="radio" slot-scope="text, record">
            <a-radio :value="record"></a-radio>
          </template>
        </a-table>
      </a-radio-group>
    </a-modal>
  </a-modal>
</template>

<script>
import moment from 'moment'
import upload from '@/components/UpLoad'
import { queryDeptList } from '@/api/systemPersonnelManage'
import {addBillReceivablePayable, updateBillReceivablePayable, queryCompanyCapitalAccountList} from '@/api/financialCenter'
const fomrMessage = `必填项不能为空`
const defaultForm = () => ({
  id: null,
  amount: '',
  capitalAccountId: '',
  capitalAccount: '',
  capitalBank: '',
  deptName: '',
  transactionAccount: '',
  transactionBank: '',
  transactionDate: '',
  remark: '',
  bankVoucher: ''
})
const CurrencyType = {
  CNY: '人民币',
  USD: '美元'
}

export default {
  props: {
    visible: Boolean,
    data: Object
  },
  components: {
    upload
  },
  data () {
    const columns = [
      {
        width: 60,
        scopedSlots: {customRender: 'radio'}
      },
      {
        title: '序号',
        width: 60,
        scopedSlots: {customRender: 'rn'}
      },
      {
        title: '资金账户',
        dataIndex: 'account',
        ellipsis: true
      },
      {
        title: '开户银行',
        dataIndex: 'bank',
        ellipsis: true,
        customRender: (text, row, index) => {
          return text || '--'
        }
      },
      {
        title: '所属公司',
        dataIndex: 'companyName',
        ellipsis: true
      },
      {
        title: '币种',
        dataIndex: 'currencyType',
        customRender: (text, row, index) => {
          return CurrencyType[text]
        }
      }
    ]

    return {
      labelCol: {span: 6},
      wrapperCol: {span: 16},
      confirmLoading: false,
      form: defaultForm(),
      rules: {
        transactionDate: [{required: true, message: fomrMessage, trigger: ['blur', 'change']}],
        capitalAccountId: [{required: true, message: fomrMessage, trigger: ['blur', 'change']}],
        amount: [{required: true, message: fomrMessage, trigger: 'blur'}],
        bankVoucher: [{required: true, message: fomrMessage, trigger: ['blur', 'change']}]
      },
      isPayOrRecevie: false,
      // modal
      accountVisible: false,
      deptTreeData: [],
      CurrencyType,
      searchForm: {
        status: '1', // 状态：1正常，0冻结
        account: '', // 资金账户
        currencyType: '', // 币种：CNY、USD
        deptId: '', // 架构id
        bank: '' // 开户行
      },
      columns,
      tableData: [],
      loading: false,
      pageNum: 1,
      pageSize: 999,
      chosenAccount: null,
      chosenItem0: '',
      chosenItem1: '',
      chosenItem2: ''
    }
  },
  computed: {
    title () {
      return this.data.id ? `编辑${this.billInfo}款记录` : `添加${this.billInfo}款记录`
    },
    amountType () {
      return this.data.currencyType === 'CNY' ? 'RMB' : (this.data.currencyType === 'USD' ? 'USD 汇率:' + this.data.rate : '?')
    },
    transactionDateMoment () {
      return this.form.transactionDate === '' ? null : moment(this.form.transactionDate)
    },
    // 金额 账号 日期
    billInfo () {
      return this.isPayOrRecevie ? '付' : '收'
    },
    // 账号, 银行
    accountInfo () {
      return this.isPayOrRecevie ? '收' : '付'
    }
  },
  methods: {
    uploadFile (e) {
      this.form.bankVoucher = e
    },
    onChangeDate (date, dataStr) {
      this.form.transactionDate = dataStr
    },
    disabledDate (current) {
      // Can not select days before today and today
      return current > moment().endOf('day')
    },
    handleOk () {
      this.$refs.rulesForm.validate(valid => {
        if (valid) {
          this.confirmLoading = true
          if (this.form.id) {
            updateBillReceivablePayable(this.form).then(rsp => {
              this.$message.success('更新成功')
              this.$emit('setData', true)
              setTimeout(() => { this.confirmLoading = false }, 1000)
            }).catch(() => { this.confirmLoading = false })
          } else {
            addBillReceivablePayable(this.form).then(rsp => {
              this.$message.success('添加成功')
              this.$emit('setData', true)
              setTimeout(() => { this.confirmLoading = false }, 1000)
            }).catch(() => { this.confirmLoading = false })
          }
        }
      })
    },
    handleCancel () {
      this.$emit('setData')
    },
    chooseAccount () {
      queryDeptList({parentId: 0}).then(rsp => {
        let initData = [{
          title: '全部',
          key: '',
          value: '',
          isLeaf: true
        }]
        rsp.data.forEach((value, index) => {
          initData.push({
            title: value.name,
            key: value.deptId,
            value: value.deptId
          })
        })
        this.deptTreeData = initData

        this.searchForm.deptId = initData[0].key
        this.handleSubmit()
      })
      this.accountVisible = true
    },
    onLoadData (treeNode) {
      return new Promise(resolve => {
        if (treeNode.dataRef.children && treeNode.dataRef.children.length > 0) {
          resolve()
          return
        }
        queryDeptList({parentId: treeNode.dataRef.key}).then(rsp => {
          let childrenData = []
          rsp.data.forEach((value) => {
            childrenData.push({
              title: value.name,
              key: value.deptId,
              value: value.deptId,
              isLeaf: true
            })
          })
          treeNode.dataRef.children = childrenData
          this.deptTreeData = [...this.deptTreeData]
          resolve()
        })
      })
    },
    handleSubmit () {
      this.loading = true
      queryCompanyCapitalAccountList({
        ...this.searchForm,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      }).then(rsp => {
        this.loading = false
        this.tableData = rsp.data.list
      }).catch(() => { this.loading = false })
    },
    handleOk2 () {
      if (this.chosenAccount) {
        this.form.capitalAccountId = this.chosenAccount.id
        this.chosenItem0 = this.chosenAccount.account
        this.chosenItem1 = this.chosenAccount.bank
        this.chosenItem2 = this.chosenAccount.companyName
        this.accountVisible = false
      } else {
        this.$message.error('请选择一个资金账户')
      }
    },
    handleCancel2 () {
      this.accountVisible = false
    }
  },
  watch: {
    visible () {
      if (this.visible) {
        this.chosenAccount = null
        this.chosenItem0 = ''
        this.chosenItem1 = ''
        this.chosenItem2 = ''
        if (this.data.id) {
          Object.assign(this.form, this.data)
        } else {
          Object.assign(this.form, this.data, defaultForm())
        }
        this.isPayOrRecevie = this.data.isPayOrRecevie
      }
    }
  }
}
</script>

<style lang="less" scoped>

</style>
